#!/usr/bin/env python

from django import template
from django.utils.html import format_html
from datetime import datetime
from bbs import models
from django.db.models import Count

register = template.Library()


@register.filter
def truncate_url(img_obj):
    if len(img_obj) == 0:
        head_img = 'images/default_head_img.jpg'
    else:
        head_img = img_obj.name.split("/", maxsplit=1)[-1]
    return head_img


@register.simple_tag
def filter_comment(article_obj):
    """
    获取每条
    :param article_obj:
    :return:
    """
    common_count = thumb_count = 0
    # query_set = article_obj.comment_set.select_related()
    common_counts = models.Comment.objects.filter(article_id=article_obj.id).values('comment_type').annotate(
        commnum=Count('*'))
    # print('Count:', common_counts)
    for c in common_counts:
        if c['comment_type'] == 1:
            common_count = c['commnum']
        else:
            thumb_count = c['commnum']
    comments = {
        'comment_count': common_count,
        'thumb_count': thumb_count,
    }
    return comments


@register.filter
def readable_date(pub_date):
    curr_date = datetime.now()
    diff = curr_date - pub_date.replace(tzinfo=None)
    total_second = diff.total_seconds()
    if total_second >= 86400:
        date_between = str(int(divmod(total_second, 86400)[0])) + '天前'
    elif total_second >= 3600:
        date_between = str(int(divmod(total_second, 3600)[0])) + '小时前'
    elif total_second >= 60:
        date_between = str(int(divmod(total_second, 60)[0])) + '分钟前'
    else:
        date_between = '刚刚'

    return date_between


@register.simple_tag()
def common_tree(common_list):
    """
    生成评论树
    :param common_list:
    :return:
    """
    return_str = ""
    for common in common_list:  # 开始遍历按顺序插入的评论列表
        #print(common['id'], common['pid'])
        if common['pid'] is None:  # 如果是父评论
            return_str += "<li class='commli'>"
            return_str = return_str + " <span class='p1'><img src='/static/" + truncate_url(common['img']) + \
                         "' class='img1'>  " + common['author'] + "</span><span class='p2'>" + \
                         common['content'] + "</span><span class='p3'>" + readable_date(common['pubdate']) \
                         + "</span><span ><a class='p4' onclick='article_thumbup(this," + str(common['article_id']) + ",2," \
                         + str(common['id'])+",\"\",\"\")'><i class='glyphicon glyphicon-thumbs-up'></i> 顶[<label>"+str(common['thumb_up_count'])+"</label>]</a></span>" \
                         + "<span class='p5'><a class='p5' onclick='tree_common(this," + str(common['article_id']) + ",1,"+str(common['id'])+")'><i class='glyphicon glyphicon-pencil'></i> 回复</a></span>"
            # return_str = return_str + common['content']
            return_str += "</li>"
            return_str = build_subcommon(common['id'], common_list, return_str)  # 获取父评论下的所有子评论
    # print(return_str)
    return format_html(return_str)


def build_subcommon(currid, common_list, buildstr):
    """
    获取父评论下的所有子评论
    :param currid: 父评论ID
    :param common_list: 遍历的源列表
    :param buildstr: 组合字符串
    :return:
    """
    for common in common_list:
        if common['pid'] == currid:  # 如果当前评论的父ID为要查找的ID
            buildstr += "<li><ul>"
            buildstr += "<li>"
            buildstr = buildstr + " <span class='p1'><img src='/static/" + truncate_url(common['img']) + \
                         "' class='img1'>  " + common['author'] + "</span><span class='p2'>" + \
                         common['content'] + "</span><span class='p3'>" + readable_date(common['pubdate']) \
                         + "</span><span ><a class='p4' onclick='article_thumbup(this," + str(common['article_id']) + ",2," \
                         + str(common['id'])+",\"\",\"\")'><i class='glyphicon glyphicon-thumbs-up'></i> 顶[<label>"+str(common['thumb_up_count'])+"</label>]</a></span>" \
                         + "<span ><a class='p5' onclick='tree_common(this," + str(common['article_id']) + ",1,"+str(common['id'])+")'><i class='glyphicon glyphicon-pencil'></i> 回复</a></span>"
            # buildstr = buildstr + common['content']
            buildstr += "</li>"
            buildstr = build_subcommon(common['id'], common_list, buildstr)  # 递归当前评论是否还有子评论
            buildstr += "</ul></li>"
    # print("end all loop sub ",currid, buildstr)
    return buildstr

@register.filter
def show_html(content):
    return format_html(content)
